package com.kmzx.one.project.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kmzx.one.common.utils.MyAssert;
import com.kmzx.one.common.utils.UUIDGenerator;
import com.kmzx.one.project.config.data.WXDataConfig;
import com.kmzx.one.project.entity.RankTab;
import com.kmzx.one.project.entity.WxUser;
import com.kmzx.one.project.net.BaseResult;
import com.kmzx.one.project.net.UserResult;
import com.kmzx.one.project.others.dto.FastZoneOutInfo;
import com.kmzx.one.project.others.dto.FriendPic;
import com.kmzx.one.project.others.dto.MemberActionInfo;
import com.kmzx.one.project.others.dto.MemberCenter;
import com.kmzx.one.project.others.dto.UserAuthInfo;
import com.kmzx.one.project.others.dto.UserCenterInfo;
import com.kmzx.one.project.others.dto.UserCert;
import com.kmzx.one.project.others.dto.UserCertInfo;
import com.kmzx.one.project.others.dto.UserVerifyInfo;
import com.kmzx.one.project.others.vos.WXOpenId;
import com.kmzx.one.project.others.vos.WxEnUserInfo;
import com.kmzx.one.project.service.ExpandUserService;
import com.kmzx.one.project.service.ProdService;
import com.kmzx.one.project.service.UserCenterService;
import com.kmzx.one.project.service.UserMessageService;
import com.qq.weixin.mp.aes.PKCS7Encoder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import weixin.popular.client.LocalHttpClient;
import weixin.popular.util.EmojiUtil;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Api(tags = "快美甄选_[ 用户_会员_接口 ]")
@RestController
public class UserSelfController extends BaseController {

    protected static Header jsonHeader = new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());

    @Autowired
    private WXDataConfig wxConfig;

    @Autowired
    private UserCenterService userCenterService;


    @Autowired
    private ProdService prodService;

    @Autowired
    private UserMessageService userMessageService;

    @Autowired
    ExpandUserService expandUserService;

    /**
     * 获取用户的openId
     *
     * @param jsCode
     * @return
     */

    @ApiOperation(value = "1.获取用户的openId(如果已经注册过,则包含userId)", notes = "获取用户的openId(如果已经注册过,则包含userId)")
    @GetMapping(value = "user/getOpenId")
    public UserResult getUserOpenId(@Valid @RequestParam("jsCode") String jsCode, HttpServletRequest request) {
        HttpUriRequest httpUriRequest = getHttpUriRequest(jsCode);
        logger.info("当前用户的js_code为:{}", jsCode);
        try {
            WXOpenId result = LocalHttpClient.executeJsonResult(httpUriRequest, WXOpenId.class);
            logger.info("WXOpenId 请求解果为:{}", result);
            String openId = result.openId;
            UserResult userResult = UserResult.Builder.SUCC();
            if (openId != null) {
//                String encyData = request.getParameter("encyData");
//                String ivData = request.getParameter("ivData");
                userResult.setData(openId);
                userResult.setUnionId(result.getUnionid());
                WxUser wu = userCenterService.findByOpenId(openId);
                if (wu != null) {
                    userResult.setUnionId(result.getUnionid());
                    userResult.setUserId(wu.getId());
                } else {
                    String chCode = request.getParameter("channelId");
                    String prodId2 = request.getParameter("prodId2");
                    String userId = request.getParameter("userId");
                    expandUserService.addExpandUserLog(result.getUnionid(), chCode, prodId2, userId);
                }
                userResult.setSessionKey(result.getSession_key());

            } else {
                userResult.setErrCode(402);
                userResult.setErrMsg("服务器请求出错,请检查jsCode");
            }
            return userResult;
        } catch (Exception e) {
            return handleUserException(e);
        }
    }


    @ApiOperation(value = "1.获取用户的openId(如果已经注册过,则包含userId)", notes = "获取用户的openId(如果已经注册过,则包含userId)")
    @GetMapping(value = "user/getOpenId2")
    public UserResult NEWUserAndReg(@Valid @RequestParam("jsCode") String jsCode, HttpServletRequest request) {

//        boolean mgc_ = jsCode.startsWith("mgc_");
//        if (mgc_) {
//            UserResult userResult = UserResult.Builder.SUCC();
//            String openId = request.getParameter("openId");
//            String nickName = request.getParameter("nickName");
//            String avatar = request.getParameter("avatar");
//            String country = request.getParameter("country");
//            String province = request.getParameter("province");
//            String city = request.getParameter("city");
//            String gender = request.getParameter("gender");
//            String parent = request.getParameter("parent");
//            String phone = request.getParameter("phone");
//            String unionId = request.getParameter("unionId");
//
//            try {
//                WxUser wu = userCenterService.findByOpenId(openId);
//                if (wu != null) {
//                    userResult.setData(wu.getId());
//                    WxUser wxUser = new WxUser();
//                    wxUser.setOpenId(openId).setIdentityType(1)
//                            .setNickName(nickName).setAvatar(avatar)
//                            .setCountry(country).setProvince(province)
//                            .setCity(city).setGender(Integer.parseInt(gender))
//                            .setMobile(phone).setUnionId(unionId).setDeleted(0);
//                    userCenterService.doUpdateWxUser(wxUser);
//                } else {
//                    WxUser wxUser = new WxUser();
//                    String userId = UUIDGenerator.generate();
//                    wxUser.setId(userId);
//                    wxUser.setOpenId(openId).setIdentityType(1)
//                            .setNickName(nickName).setAvatar(avatar)
//                            .setCountry(country).setProvince(province)
//                            .setCity(city).setGender(Integer.parseInt(gender))
//                            .setMobile(phone).setUnionId(unionId).setDeleted(0);
//
//                    regOrUpdateUser(wxUser, parent);
//                    userResult.setData(userId);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//                return handleUserException(e);
//            }
//
//            return userResult;
//
//        } else

        {
            HttpUriRequest httpUriRequest = getHttpUriRequest(jsCode);
            logger.info("当前用户的js_code为:{}", jsCode);
            try {
                WXOpenId result = LocalHttpClient.executeJsonResult(httpUriRequest, WXOpenId.class);
                logger.info("WXOpenId 请求解果为:{}", result);
                String openId = result.openId;
                UserResult userResult = UserResult.Builder.SUCC();
                if (result.openId != null) {
                    String parent = request.getParameter("parent");
                    WxUser wu = userCenterService.findByOpenId(openId);
                    if (wu != null) {
                        userResult.setData(wu.getId());
                        String nickName = wu.getNickName();
                        if ("微信用户".equals(nickName)) {
                            String encyData = request.getParameter("encyData");
                            String ivData = request.getParameter("ivData");
                            String sessions = result.getSession_key();
                            WxEnUserInfo enUserInfo = asyncRegUser(sessions, ivData, encyData, parent);
                            if (enUserInfo != null) {
                                String avatar = enUserInfo.getAvatarUrl();
                                nickName = enUserInfo.getNickName();
                                userCenterService.updateUserInfo(wu.getId(), nickName, avatar);
                                userResult.setNickName(nickName).setAvatar(avatar);
                            }
                        } else {
                            userResult.setNickName(nickName).setAvatar(wu.getAvatar());
                        }
                    } else {
                        String encyData = request.getParameter("encyData");
                        String ivData = request.getParameter("ivData");
                        String channelId = request.getParameter("channelId");
                        String sessions = result.getSession_key();
                        WxEnUserInfo enUserInfo = asyncRegUser(sessions, ivData, encyData, parent);
                        if (enUserInfo != null) {
                            String avatar = enUserInfo.getAvatarUrl();
                            String nickName = enUserInfo.getNickName();
                            String unionId = enUserInfo.getUnionId();
                            String userId = UUIDGenerator.generate();
                            WxUser wxUser = new WxUser();
                            wxUser.setId(userId);
                            wxUser.setAvatar(avatar).setNickName(nickName).setUnionId(unionId);
                            wxUser.setOpenId(openId).setCountry(enUserInfo.getCountry())
                                    .setProvince(enUserInfo.getProvince())
                                    .setCity(enUserInfo.getCity());
                            wxUser.setIdentityType(0);
                            // 添加渠道授权
                            if (channelId != null && channelId != "") {
                                wxUser.setIdentityType(Integer.valueOf(channelId));
                            }
                            regOrUpdateUser(wxUser, parent);
                            userResult.setData(userId).setUserId(userId);
                            userResult.setAvatar(avatar).setNickName(nickName);
                        } else {
                            userResult.setErrMsg("授权超时,请重新授权");
                            userResult.setErrCode(300);
                            userResult.setCode(300);
                        }
                    }
                } else {
                    userResult.setErrCode(402);
                    userResult.setCode(402);
                    userResult.setErrMsg("授权超时,请重新授权");
                }
//                    userResult.setSessionKey(sessions);
                logger.info("响应授权登录的数据:{}", userResult);
                return userResult;
            } catch (Exception e) {
                return handleUserException(e);
            }
        }

    }


    /**
     * 用户注册
     *
     * @param wxUser 用户参数
     * @param parent 邀请人id
     * @return
     */
    @PostMapping(value = "user/reg")
    @ApiOperation(value = "2.用户注册", notes = "用户注册")
    public BaseResult regOrUpdateUser(WxUser wxUser, String parent) {
        beforeAopRepeat(">>>".concat(wxUser.getOpenId()).concat(wxUser.getNickName()));
        String nickName = wxUser.getNickName();
        String emojis = EmojiUtil.removeAllEmojis(nickName);
        wxUser.setNickName(emojis);

        try {
            WxUser oldUser = userCenterService.findByOpenId(wxUser.getOpenId());
            BaseResult success = BaseResult.Builder.SUCC();
            if (oldUser != null) {
                String oldNickName = oldUser.getNickName();
                String oldAvatar = oldUser.getAvatar();
                if (!oldNickName.equals(emojis) || !oldAvatar.equals(wxUser.getAvatar())) {
                    userCenterService.doUpdateWxUser(wxUser);
                    success.setData(oldUser.getId());
                }
            } else {
                WxUser user = userCenterService.doInsertWxUser(wxUser, parent);
                success.setData(user.getId());
            }
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }

    /**
     * 获取用户的sk
     *
     * @param jsCode
     * @param userId
     * @return
     */
    @ApiOperation(value = "11.获取用户的sessionKey", notes = "11.获取用户的sk")
    @GetMapping(value = "user/getSk")
    public BaseResult getSessionKey(String jsCode, String userId) {
        HttpUriRequest uriRequest = getHttpUriRequest(jsCode);
        WXOpenId wxOpenId = LocalHttpClient.executeJsonResult(uriRequest, WXOpenId.class);
        String openId1 = wxOpenId.getOpenId();
        if (openId1 == null) {
            BaseResult fail = BaseResult.Builder.FAIL();
            fail.setCode(400);
            fail.setErrMsg("服务器请求出错,请检查jsCode");
            fail.setMsg("服务器请求出错,请检查jsCode");
            return fail;
        } else {
            BaseResult success = BaseResult.Builder.SUCC();
            success.setData(wxOpenId.getSession_key());
            return success;
        }

    }


    /**
     * 获取用户手机号
     *
     * @param encryptedData
     * @param encryptedData
     * @param iv
     * @return
     */
    @PostMapping(value = "user/getUserPhone")
    @ApiOperation(value = "3.获取用户手机号", notes = "获取用户手机号")
    public BaseResult getUserMobile(String encryptedData, String iv, String sessionData) {
        try {
            MyAssert.notNullObject(sessionData, "sessionData 为null");
            MyAssert.notNullObject(encryptedData, "encryptedData为null");
            MyAssert.notNullObject(iv, "iv值 为null");

            BaseResult success = BaseResult.Builder.SUCC();
            String sessions = sessionData;

            byte[] keyByte = Base64.decodeBase64(sessions);


            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            Key sKeySpec = new SecretKeySpec(keyByte, "AES");
//            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, new IvParameterSpec(Base64.decodeBase64(iv)));
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(Base64.decodeBase64(iv)));
            byte[] resultByte = cipher.doFinal(Base64.decodeBase64(encryptedData));
            byte[] decode = PKCS7Encoder.decode(resultByte);
            String data = new String(decode, StandardCharsets.UTF_8);

            try {
                logger.info("获取手机号,微信返回字符串:{}", data);
                JSONObject jsonObject = JSON.parseObject(data);
                if (jsonObject != null) {
                    String number = jsonObject.getString("phoneNumber");
                    if (number != null) {
                        success.setData(number);
                    } else {
                        success = BaseResult.Builder.FAIL();
                        success.setMsg("获取手机号异常");
                    }
                } else {
                    BaseResult fail = BaseResult.Builder.FAIL();
                    return fail;
                }
//
            } catch (Exception e) {
                e.printStackTrace();
                BaseResult fail = BaseResult.Builder.FAIL();
                return fail;
            }


            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }

    private static AlgorithmParameters generateIV(byte[] iv) throws NoSuchAlgorithmException, InvalidParameterSpecException {
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }


    public HttpUriRequest getHttpUriRequest(String jsCode) {
        HttpUriRequest httpUriRequest = RequestBuilder.post()
                .setHeader(jsonHeader)
                .setUri(wxConfig.getWxUrl())
                .addParameter("appid", wxConfig.getAppId())
                .addParameter("secret", wxConfig.getAppSecret())
                .addParameter("js_code", jsCode)
                .addParameter("grant_type", "authorization_code")
                .build();
        return httpUriRequest;
    }

    public HttpUriRequest getHttpUriRequestMGC(String jsCode) {
        HttpUriRequest httpUriRequest = RequestBuilder.post()
                .setHeader(jsonHeader)
                .setUri("http://search.mgc-games.com:8711/api/sns/jscode2session")
                .addParameter("appid", wxConfig.getAppId())
                .addParameter("secret", wxConfig.getAppSecret())
                .addParameter("js_code", jsCode)
                .addParameter("grant_type", "authorization_code")
                .build();
        return httpUriRequest;
    }

    public HttpUriRequest getHttpUriRequestMGC2(String jsCode) {
        HttpUriRequest httpUriRequest = RequestBuilder.post()
                .setHeader(jsonHeader)
                .setUri("http://search.mgc-games.com:8711/api/sns/jscode2session?appid=1001660&secret=5406146d1ae14ae0d53d33cb1786f7af&js_code=" + jsCode + "&grant_type=authorization_code")
//                .addParameter("appid", wxConfig.getAppId())
//                .addParameter("secret", wxConfig.getAppSecret())
//                .addParameter("js_code", jsCode)
//                .addParameter("grant_type", "authorization_code")
                .build();
        return httpUriRequest;
    }


    @ApiOperation(value = "4.获取用户的(等级,记录值)信息", notes = "获取用户的(等级,记录值)信息")
    @GetMapping(value = "user/getMainInfo")
    public BaseResult findUserMainInfo(String userId) {
        try {
            MyAssert.notNullObject(userId, "userId 为null");
            UserCenterInfo info = userCenterService.findUserTopInfo(userId);
            FastZoneOutInfo fastZone = prodService.findFastZone(userId);
            info.setFast(fastZone);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }

    @ApiOperation(value = "5.获取用户的(订单)信息", notes = "获取用户的(订单)信息")
    @GetMapping(value = "user/getExtraInfo")
    public BaseResult findUserExtraInfo(String userId) {
        try {
            MyAssert.notNullObject(userId, "userId 为null");
            UserCenterInfo info = userCenterService.findUserTwoInfo(userId);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }

    @ApiOperation(value = "6.获取用户的头像", notes = "获取用户的头像")
    @GetMapping(value = "user/downloadIcon")
    public void downloadPics(String pics, HttpServletResponse response) {
        try {
            if (pics == null) {
                BaseResult result = BaseResult.Builder.FAIL().setErrCode(402).setErrMsg("数据为空!");
                response.getWriter().println(result);
            } else if (pics.length() < 8) {
                BaseResult result = BaseResult.Builder.FAIL().setErrCode(402).setErrMsg("数据长度非法!");
                response.getWriter().println(result);
            }
            URL url = new URL(pics);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(3 * 1000);
            response.setContentType("application/force-download");// 设置强制下载不打开            
            response.addHeader("Content-Disposition", "attachment;fileName=" + "a.jpg");
            //得到输入流
            InputStream inputStream = conn.getInputStream();

            OutputStream outputStream = response.getOutputStream();

            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.close();
        } catch (Exception e) {
            BaseResult result = BaseResult.Builder.FAIL().setErrCode(402).setErrMsg("数据为空!");
            try {
                response.getWriter().print(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return;
        }
    }

    @ApiOperation(value = "7.检测用户是否有 管家", notes = "检测用户是否有 管家")
    @GetMapping(value = "user/hasFather")
    public BaseResult hasFather(String userId) {
        try {
            MyAssert.notNullObject(userId, "userId 为null");
            int info = userCenterService.doHasFather(userId);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }


    @ApiOperation(value = "8.进行用户认证")
    @PostMapping(value = "user/auth")
    public BaseResult doUserAuth(String userId, String name, String idCard) {
        try {
            MyAssert.notNullObject(userId, "userId 为null");
            UserAuthInfo info = userCenterService.doUserAuth(userId, name, idCard);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }


    @ApiOperation(value = "9.检测用户是否 认证")
    @GetMapping(value = "user/hasAuth")
    public BaseResult checkUserAuth(String userId) {
        try {
            MyAssert.notNullObject(userId, "userId 为null");
            UserAuthInfo info = userCenterService.doCheckUserAuth(userId);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }

    @ApiOperation(value = "10.分享海报")
    @GetMapping(value = "user/share")
    public BaseResult findUserShareMini(String userId) {
        try {
            MyAssert.notNullObject(userId, "userId 为null");
            String info = userCenterService.findUserShareMini(userId);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }

    @ApiOperation(value = "12.更新昵称头像")
    @PostMapping(value = "user/updateInfo")
    public BaseResult pushUserInfo(String userId, String nickName, String avatar) {
        try {
            MyAssert.notNullObject(userId, "userId 为null");
            userCenterService.updateUserInfo(userId, nickName, avatar);
            BaseResult success = BaseResult.Builder.SUCC();
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }

    public WxEnUserInfo asyncRegUser(String sessions, String ivData, String encyData, String parent) {
        try {
            byte[] keyByte = Base64.decodeBase64(sessions);


            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            Key sKeySpec = new SecretKeySpec(keyByte, "AES");
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(Base64.decodeBase64(ivData)));
            byte[] resultByte = cipher.doFinal(Base64.decodeBase64(encyData));
            byte[] decode = PKCS7Encoder.decode(resultByte);
            String data = new String(decode, StandardCharsets.UTF_8);

            WxEnUserInfo wxEnUserInfo = JSON.parseObject(data, WxEnUserInfo.class);
            return wxEnUserInfo;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (InvalidParameterSpecException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (Exception e) {

        }
        return null;

    }

    @ApiOperation(value = "13.检测unionId")
    @GetMapping(value = "user/checkUnion")
    public BaseResult checkUserUnionId(String userId) {
        try {
            MyAssert.notNullObject(userId, "userId 为null");
            boolean b = userCenterService.checkUserUnionId(userId);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(b);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }


    @ApiOperation(value = "14.检测用户是否 提交过实名信息")
    @GetMapping(value = "user/hasCert")
    public BaseResult checkUserCert(String userId) {
        try {
            MyAssert.notNullObject(userId, "userId 为null");
            UserCertInfo info = userCenterService.checkUserCertInfo(userId);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }

    @ApiOperation(value = "15.提交 实名信息")
    @PostMapping(value = "user/doCert")
    public BaseResult doUserCert(UserCert userCert) {
        try {
            userCenterService.doUserCertInfo(userCert);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(200);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }

    @ApiOperation(value = "16.订单_检测用户是否 提交过实名信息")
    @GetMapping(value = "user/hasVerify")
    public BaseResult checkUserVerify(String userId) {
        try {
            MyAssert.notNullObject(userId, "userId 为null");
            UserVerifyInfo info = userCenterService.checkUserVerifyInfo(userId);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }

    @ApiOperation(value = "17.订单_提交 实名信息")
    @PostMapping(value = "user/doVerify")
    public BaseResult doUserVerify(String userId, String username, String idCard, String phone) {
        try {
            beforeAopRepeat(">>>".concat(userId).concat(username).concat(idCard).concat(phone));
            MyAssert.notNullObject(userId, "用户信息 为空");
            MyAssert.notNullObject(username, "姓名 为空");
            MyAssert.notNullObject(idCard, "身份证号 为空");
            MyAssert.notNullObject(phone, "手机号 为空");
            userCenterService.doUserVerifyInfo(userId, username, idCard, phone);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(200);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }

    @ApiOperation(value = "18.获取会员级别图片", position = -1)
    @GetMapping(value = "user/memberCenter")
    public BaseResult userMemberCenter(String userId) {
        try {
            MyAssert.notNullObject(userId, "userId 为null");
            RankTab rankTab = userMessageService.findUserMemberRank(userId);
            List<MemberCenter> memberCenters = userMessageService.findMemberCenter();
            if (memberCenters.size() > 0) {
                MemberCenter memberCenter = new MemberCenter();
                Optional<MemberCenter> satisfyMember = memberCenters.stream().filter(f -> f.getSatisfy().equals(0)).findFirst();
                Optional<MemberCenter> member = memberCenters.stream().filter(f -> f.getSatisfy().equals(1)).findFirst();
                switch (rankTab.getRankNumber()) {
                    case 0:
                        memberCenter.setVipUrl(satisfyMember.get().getVipUrl());
                        memberCenter.setSvipUrl(satisfyMember.get().getSvipUrl());
                        memberCenter.setPartnerUrl(satisfyMember.get().getPartnerUrl());
                        break;
                    case 1:
                        memberCenter.setVipUrl(member.get().getVipUrl());
                        memberCenter.setSvipUrl(satisfyMember.get().getSvipUrl());
                        memberCenter.setPartnerUrl(satisfyMember.get().getPartnerUrl());
                        break;
                    case 2:
                        memberCenter.setVipUrl(member.get().getVipUrl());
                        memberCenter.setSvipUrl(member.get().getSvipUrl());
                        memberCenter.setPartnerUrl(satisfyMember.get().getPartnerUrl());
                        break;
                    case 3:
                        memberCenter.setVipUrl(member.get().getVipUrl());
                        memberCenter.setSvipUrl(member.get().getSvipUrl());
                        memberCenter.setPartnerUrl(member.get().getPartnerUrl());
                        break;
                }
                return BaseResult.Builder.SUCC().initSuccData(memberCenter);
            }
        } catch (Exception e) {
            return handleException(e);
        }
        return BaseResult.Builder.FAIL();
    }

    @ApiOperation(value = "19.获取邀请好友图片", position = -1)
    @GetMapping(value = "user/friendPic")
    public BaseResult userFriendPic() {
        try {
            List<FriendPic> friendPics = userMessageService.findFriendPic();
            if (friendPics.size() > 0) {
                return BaseResult.Builder.SUCC().initSuccData(friendPics.get(0));
            }
        } catch (Exception e) {
            return handleException(e);
        }
        return BaseResult.Builder.FAIL();
    }

    @ApiOperation(value = "19.会员等级图片", position = -1)
    @GetMapping(value = "user/rankPic")
    public BaseResult findUserMemberPic(String userId) {
        try {
            MyAssert.notNullObject(userId, "userId 为null");
            RankTab rankTab = userMessageService.findUserMemberRank(userId);
            List<MemberCenter> memberCenters = userMessageService.findMemberCenter();
            if (memberCenters.size() > 0) {
                List<MemberActionInfo> actionInfos = userMessageService.findMemberActionUpInfo();
                MemberCenter memberCenter = new MemberCenter();
                memberCenter.setVipUrl(actionInfos.get(0).getFastId());
                memberCenter.setSvipUrl(actionInfos.get(1).getFastId());
                Optional<MemberCenter> satisfyMember = memberCenters.stream().filter(f -> f.getSatisfy().equals(0)).findFirst();
                Optional<MemberCenter> member = memberCenters.stream().filter(f -> f.getSatisfy().equals(1)).findFirst();
                switch (rankTab.getRankNumber()) {
                    case 0:

                        memberCenter.setVipImg(satisfyMember.get().getVipUrl());
                        memberCenter.setSvipImg(satisfyMember.get().getSvipUrl());
                        memberCenter.setPartnerUrl(satisfyMember.get().getPartnerUrl());
                        break;
                    case 1:
                        memberCenter.setVipImg(member.get().getVipUrl());
                        memberCenter.setSvipImg(satisfyMember.get().getSvipUrl());
                        memberCenter.setPartnerUrl(satisfyMember.get().getPartnerUrl());
                        break;
                    case 2:
                        memberCenter.setVipImg(member.get().getVipUrl());
                        memberCenter.setSvipImg(member.get().getSvipUrl());
                        memberCenter.setPartnerUrl(satisfyMember.get().getPartnerUrl());
                        break;
                    case 3:
                        memberCenter.setVipImg(member.get().getVipUrl());
                        memberCenter.setSvipImg(member.get().getSvipUrl());
                        memberCenter.setPartnerUrl(member.get().getPartnerUrl());
                        break;
                }
                return BaseResult.Builder.SUCC().initSuccData(memberCenter);
            }
        } catch (Exception e) {
            return handleException(e);
        }
        return BaseResult.Builder.FAIL();
    }

}
